//
//  RSWebViewViewController.m
//  WebView范例
//
//  Created by 王文 on 2017/3/3.
//  Copyright © 2017年 王文. All rights reserved.
//

#import "RSWebViewViewController.h"
#import <WebKit/WebKit.h>
#import "UIButton+WHE.h"

@interface RSWebViewViewController ()<WKNavigationDelegate,WKUIDelegate>

@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) UIProgressView *progressView;

@end

@implementation RSWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self addBackBtn];
    [self addWKWebView];
    [self addProgressView];
    
}
-(void)addWKWebView {
    //创建WKWwebView
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    self.webView = webView;
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    //创建url
    NSURL *URL = [NSURL URLWithString:@"https://www.baidu.com"];
    //创建request
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    //加载request
    [webView loadRequest:request];
    [self.view addSubview:webView];
    
}
-(void)addProgressView {
    //进度条初始化
    self.progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, 2)];
    self.progressView.backgroundColor = [UIColor blueColor];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view insertSubview:self.progressView aboveSubview:self.webView];
}
-(void)addBackBtn {
    UIView * customView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 88, 44)];
    UIButton *backBtn = [UIButton buttonBackWithImage:[UIImage imageNamed:@"backBtn"] buttontitle:@"返回" target:self action:@selector(clickedbackBtn:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [customView addSubview:backBtn];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:customView];
}
-(void)addCloseBtn{
    
    UIView * customView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 88, 44)];
    
    UIButton *backBtn = [UIButton buttonBackWithImage:[UIImage imageNamed:@"backBtn"] buttontitle:@"返回" target:self action:@selector(clickedbackBtn:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [customView addSubview:backBtn];
    
    UIButton *closeBtn = [[UIButton alloc] init];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [closeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [closeBtn addTarget:self action:@selector(clickedcloseBtn:) forControlEvents:UIControlEventTouchUpInside];
    closeBtn.frame = CGRectMake(38, 0, 44, 44);
    [closeBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [customView addSubview:closeBtn];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView];
}
-(void)clickedcloseBtn:(UIButton*)btn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)clickedbackBtn:(UIButton*)btn{
    if (self.webView.canGoBack) {
        [self addCloseBtn];
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"estimatedProgress"]) {
//        self.progressView.progress = self.webView.estimatedProgress;
//        if (self.progressView.progress == 1) {
//            /*
//             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
//             *动画时长0.25s，延时0.3s后开始动画
//             *动画结束后将progressView隐藏
//             */
//            __weak typeof (self)weakSelf = self;
//            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
//                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
//            } completion:^(BOOL finished) {
//                weakSelf.progressView.hidden = YES;
//                
//            }];
//        }
//    }else{
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//    }
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        NSLog(@"webView的加载进度：%f",newprogress);
        if (newprogress == 1)
        {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }
        else
        {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}
#pragma mark WKNavigationDelegate-----
///* 1.在发送请求之前，决定是否跳转  */
//- (void)webView:(WKWebView *)webView
//decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
//decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    
//}
/* 2.页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    [self.progressView setProgress:0.1 animated:YES];
}
///* 3.在收到服务器的响应头，根据response相关信息，决定是否跳转。 */
//- (void)webView:(WKWebView *)webView
//decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
//decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//    
//}
///* 4.开始获取到网页内容时返回，需要注入JS，在这里添加 */
//- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
//    
//}
/* 5.页面加载完成之后调用 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
}
/* error - 页面加载失败时调用 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"加载失败");
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}
///* 其他 - 处理服务器重定向Redirect */
//- (void)webView:(WKWebView *)webView
//didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
//    
//}
//#pragma mark WKUIDelegate-----
///* 输入框，页面中有调用JS的 prompt 方法就会调用该方法 */
//- (void)webView:(WKWebView *)webView
//runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt
//    defaultText:(nullable NSString *)defaultText
//initiatedByFrame:(WKFrameInfo *)frame
//completionHandler:(void (^)(NSString *result))completionHandler {
//    
//}
///* 确认框，页面中有调用JS的 confirm 方法就会调用该方法 */
//- (void)webView:(WKWebView *)webView
//runJavaScriptConfirmPanelWithMessage:(NSString *)message
//initiatedByFrame:(WKFrameInfo *)frame
//completionHandler:(void (^)(BOOL result))completionHandler {
//    
//}
///* 警告框，页面中有调用JS的 alert 方法就会调用该方法 */
//- (void)webView:(WKWebView *)webView
//runJavaScriptAlertPanelWithMessage:(NSString *)message
//initiatedByFrame:(WKFrameInfo *)frame
//completionHandler:(void (^)(void))completionHandler {
//    
//}
///*加载请求*/
//- (WKNavigation *)loadRequest:(NSURLRequest *)request;
///*加载本地HTML字符串*/
//- (WKNavigation *)loadHTMLString:(NSString *)string
//                         baseURL:(nullable NSURL *)baseURL;
///*加载本地文件*/
//- (WKNavigation *)loadFileURL:(NSURL*)url
//      allowingReadAccessToURL:(NSURL*)url;
///* 加载二进制数据 */
//- (WKNavigation *)loadData:(NSData *)data
//                  MIMEType:(NSString *)MIMEType
//     characterEncodingName:(NSString *)characterEncodingName
//                   baseURL:(NSURL *)baseURL;
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
